//
//  BannerView.m
//  轮播图
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 张树林. All rights reserved.
//

#import "SLBannerView.h"
#import <UIImageView+WebCache.h>

#define WIDTH self.bounds.size.width
#define HEIGHT self.bounds.size.height


@interface SLBannerView () <UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UIView *titleBackView;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UILabel *currentPageLabel;
@property (strong, nonatomic) UILabel *totalPageLabel;
@property (strong, nonatomic) NSMutableArray *imageArray;
@property (assign, nonatomic) NSInteger scrollIndex;
@property (strong, nonatomic) NSTimer *timer;

@end


@implementation SLBannerView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self createScrollView];
    }
    
    return self;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createScrollView];
    }
    
    return self;
}


+ (instancetype)bannerWithFrame:(CGRect)frame actionBlock:(ACTION_BLOCK)block
{
    SLBannerView *bannerview = [[SLBannerView alloc] initWithFrame:frame];
    bannerview.block = block;
    
    return bannerview;
}


+ (instancetype)bannerWithImageURLArray:(NSArray *)imageURLStrArray
                          titleStrArray:(NSArray *)titleStrArray
                            actionBlock:(ACTION_BLOCK)block
{
    SLBannerView *bannerView = [[SLBannerView alloc] init];
    bannerView.imageURLStrArray = imageURLStrArray;
    bannerView.titleStrArray = titleStrArray;
    bannerView.block = block;
    
    return bannerView;
}


- (void)setImageURLStrArray:(NSArray *)imageURLStrArray
{
    if (_imageURLStrArray != imageURLStrArray) {
        _imageURLStrArray = imageURLStrArray;
    }
    
    if (_imageURLStrArray) {
        [self createScrollViewSubViews];
    }
}


- (void)setTitleStrArray:(NSArray *)titleStrArray
{
    if (_titleStrArray != titleStrArray) {
        _titleStrArray = titleStrArray;
    }
    
    if (_titleStrArray) {
        [self createTitleLabel];
    }
    
}


- (void)createTitleLabel
{
    // 把上一个titleLabel从scrollview中移除
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[UILabel class]] || [subView isMemberOfClass:[UIView class]]) {
            [subView removeFromSuperview];
        }
    }
    
//    [self.timer setFireDate:[NSDate date]];
    
    self.titleBackView = [[UIView alloc] init];
    [self addSubview:self.titleBackView];
    self.titleBackView.backgroundColor = [UIColor blackColor];
    self.titleBackView.alpha = 0.3;
    
    self.titleLabel = [[UILabel alloc] init];
    [self addSubview:self.titleLabel];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = self.titleStrArray[0];
//    self.titleLabel.layer.borderWidth = 1;
//    self.titleLabel.layer.borderColor = [UIColor redColor].CGColor;
    
    self.currentPageLabel = [[UILabel alloc] init];
    [self addSubview:self.currentPageLabel];
    self.currentPageLabel.font = [UIFont systemFontOfSize:19];
    self.currentPageLabel.textColor = [UIColor orangeColor];
    self.currentPageLabel.textAlignment = NSTextAlignmentRight;
//    self.currentPageLabel.layer.borderWidth = 1;
//    self.currentPageLabel.layer.borderColor = [UIColor blueColor].CGColor;
    self.currentPageLabel.text = @"1";
    
    self.totalPageLabel = [[UILabel alloc] init];
    [self addSubview:self.totalPageLabel];
    self.totalPageLabel.textColor = [UIColor whiteColor];
    self.totalPageLabel.font = [UIFont systemFontOfSize:12];
    self.totalPageLabel.textAlignment = NSTextAlignmentLeft;
//    self.totalPageLabel.layer.borderWidth = 1;
//    self.totalPageLabel.layer.borderColor = [UIColor greenColor].CGColor;
    self.totalPageLabel.text = [NSString stringWithFormat:@"/%ld", self.titleStrArray.count];
    
    CGFloat titleBackX = 0;
    CGFloat titleBackH = 30;
    CGFloat titleBackW = WIDTH;
    CGFloat titleBackY = HEIGHT - titleBackH;
    self.titleBackView.frame = CGRectMake(titleBackX, titleBackY, titleBackW, titleBackH);
    
    CGFloat titleLabelX = 13;
    CGFloat titleLabelY = titleBackY;
    CGFloat titleLabelW = titleBackW - 65;
    CGFloat titleLabelH = titleBackH;
    self.titleLabel.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);

    CGFloat currentX = CGRectGetMaxX(self.titleLabel.frame);
    CGFloat currentY = titleLabelY;
    CGFloat currentH = 18;
    CGFloat currentW = 25;
    self.currentPageLabel.frame = CGRectMake(currentX, currentY, currentW, currentH);
    
    CGFloat totalX = CGRectGetMaxX(self.currentPageLabel.frame);
    CGFloat totalH = 16;
    CGFloat totalY = currentY + (currentH - totalH);
    CGFloat totalW = 25;
    self.totalPageLabel.frame = CGRectMake(totalX, totalY, totalW, totalH);
}


- (void)createScrollView
{
    self.scrollView = [[UIScrollView alloc] init];
    [self addSubview:self.scrollView];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    if (! self.timeInterval) {
        self.timeInterval = 4;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timeInterval target:self selector:@selector(timerChangeAction) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]];
}


- (void)createScrollViewSubViews
{
    // 把上一个轮播图的图片从轮播图中移除
    for (UIView *subView in self.scrollView.subviews) {
        if ([subView isKindOfClass:[UIImageView class]]) {
            [subView removeFromSuperview];
        }
    }
    
    NSInteger count = self.imageURLStrArray.count;
    
    if (1 == count) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.scrollView.bounds];
        [self.scrollView addSubview:imageView];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageURLStrArray[0]] placeholderImage:[UIImage imageNamed:@"pac.png"]];
        
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageAction:)];
        imageView.tag = 100;
        [imageView addGestureRecognizer:tap];
        
        [self.timer setFireDate:[NSDate distantFuture]];
        
        return;
    } else if (0 == count) {
        return;
    }
    
    self.scrollView.contentSize = CGSizeMake((count + 2) * WIDTH, HEIGHT);
    self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
    self.scrollIndex = 0;
    self.scrollView.delegate = self;
    self.scrollView.bounces = NO;
    [self.timer setFireDate:[NSDate date]];
    
    
    for (NSInteger i = 0; i < count + 2; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        [self.scrollView addSubview:imageView];
        [self.imageArray addObject:imageView];
        
        if (0 == i) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageURLStrArray[count - 1]] placeholderImage:[UIImage imageNamed:@"pac.png"]];
        } else if (count + 1 == i) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageURLStrArray[0]] placeholderImage:[UIImage imageNamed:@"pac.png"]];
        } else {
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageURLStrArray[i - 1]] placeholderImage:[UIImage imageNamed:@"pac.png"]];
            
            imageView.tag = 100 + i - 1;
            
            // 添加手势
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageAction:)];
            [imageView addGestureRecognizer:tap];
        }
        
        CGFloat imageX = i * WIDTH;
        CGFloat imageY = 0;
        CGFloat imageW = WIDTH;
        CGFloat imageH = HEIGHT;
        imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
    }
    
}


- (void)timerChangeAction
{
    NSInteger count = self.imageURLStrArray.count;
    
    [self.scrollView setContentOffset:CGPointMake((self.scrollIndex + 1) * WIDTH, 0) animated:YES];

    if (self.scrollIndex == count) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
        self.scrollIndex = 0;
    }
    
    self.titleLabel.text = self.titleStrArray[self.scrollIndex];
    self.currentPageLabel.text = [NSString stringWithFormat:@"%ld", self.scrollIndex + 1];
    
    self.scrollIndex++;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger count = self.imageURLStrArray.count;
    
    if (scrollView.contentOffset.x == 0) {
        scrollView.contentOffset = CGPointMake(count * WIDTH, 0);
    } else if (scrollView.contentOffset.x == (count + 1) * WIDTH) {
        scrollView.contentOffset = CGPointMake(WIDTH, 0);
    }
    
    self.scrollIndex = scrollView.contentOffset.x / WIDTH - 1;
//    NSLog(@"index ==== %ld", self.scrollIndex);
    
    // 切换titleLabel内容
    self.titleLabel.text = self.titleStrArray[self.scrollIndex];
    self.currentPageLabel.text = [NSString stringWithFormat:@"%ld", self.scrollIndex + 1];
}


- (void)layoutSubviews
{
    CGFloat scrollX = 0;
    CGFloat scrollY = 0;
    CGFloat scrollW = WIDTH;
    CGFloat scrollH = HEIGHT;
    self.scrollView.frame = CGRectMake(scrollX, scrollY, scrollW, scrollH);
}


- (void)tapImageAction:(UIGestureRecognizer *)tap
{
    UIImageView *imageView = (UIImageView *)tap.view;
    NSInteger tag = imageView.tag;
    NSInteger imageIndex = tag - 100;
    
    if (self.block) {
        self.block(imageIndex);
    }
}


@end
